// src/views/login/Index.tsx
import { Form, Input, Button, message } from 'antd'
import {
  UserOutlined,
  LockOutlined
} from '@ant-design/icons'
import { useNavigate, useLocation } from 'react-router-dom'
// 导入封装好的 接口约束 及 调用方法
import { IAdminParams, adminLoginFn } from '../../api/user'
// 导入 RTK 相关基础操作信息
import { useAppDispatch } from '../../store/hooks';
import { changeAdminName, changeCheckedkeys, changeLoginState, changeRole, changeToken } from '../../store/modules/user';


type IndexProps = {}

const Index = (props: IndexProps) => {
  // 拿到 redux 中的方法
  const dispatch = useAppDispatch()
  const navigate = useNavigate()

  // 拿到登录之后的参数
  const { search } = useLocation()
  const redirectUrl = search.split('?r=')[1]

  const onFinish = (values: IAdminParams) => {
    console.log(values)

    adminLoginFn(values).then(res => {
      console.log(res.data)
      switch (res.data.code) {
        case '10005':
          message.error('不存在该账户')
          break;
        case '10003':
          message.error('密码错误')
          break;
        default:
          message.success('登录成功')
          // 在 RTK 中存储信息到本地进行状态管理
          const result = res.data.data
          dispatch(changeLoginState(true))
          dispatch(changeAdminName(result.adminname))
          dispatch(changeToken(result.token))
          dispatch(changeRole(result.role))
          dispatch(changeCheckedkeys(result.checkedkeys))
          // 应该要跳转到系统首页
          // navigate('/', { replace: true })
          redirectUrl ? navigate(redirectUrl, { replace: true }) : navigate('/', { replace: true })
          break;
      }
    })
  }
  return (
    <div id='components-form-demo-normal-login'>
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{ remember: true }}
        onFinish={onFinish}
      >
        <h1>嗨购管理系统</h1>
        {/* 一定要记得把原来组件库的userName改成 adminname */}
        <Form.Item
          name="adminname"
          rules={[{ required: true, message: '请输入管理员账户!' }]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="管理员账户" allowClear />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="密码"
            allowClear
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">
            登 录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
export default Index